<template>
  <div class="login">
    <div class="logo">
      <img :src="require('../../assets/login.png')" width="100%">
    </div>
    <el-form ref="form" :model="form" :status-icon="true"  :hide-required-asterisk="true"  :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username" >
        <el-input v-model="form.username" maxlength="16" minlength="6"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" maxlength="16" minlength="6"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code" :inline="true">
        <el-input v-model="form.code" style="width: calc(100% - 95px)"></el-input>
        <img alt="验证码" :src="codeImgUrl" @click="codeClick" style=" height: 40px; width: 95px;float: right"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import url from '@/URL'
  export default {
    created(){
      this.codeClick()
    },
    data() {
      return {
        codeImgUrl: '',
        form: {
          username: '',
          password: '',
          code: ''
        },
        rules:{
          username:[
            {required:true , message: '用户名不能为空' ,trigger: 'blur'},
            {min:6,max:16, message: '输入6-16位用户名' , trigger: 'blur'}
          ],
          password:[
            {required:true , message: '密码不能为空' ,trigger: 'blur'},
            {min:6,max:16, message: '输入6-16位密码', trigger: 'blur'}
          ],
          code:[
            {required:true , message: '验证码不能为空' ,trigger: 'blur'},
            {min:4,max:4, message: '输入4位验证码', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      onSubmit() {
        let _this  = this
        this.$refs['form'].validate((valid) => {
          if (valid) {
            console.log(_this.form)
            _this.$apiSys.login({"username": _this.form.username,"password": _this.form.password,"code":_this.form.code}).then(res=>{
              if (res.code===1){
                _this.$router.push({path:"/Sys/Index"})
              }
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      codeClick () {
        //date="+ Math.random(); 防止缓存
        this.codeImgUrl = url.target + "/sys/code?date="+ Math.random();
      }
    },
  }
</script>

<style scoped>
  .logo{
    height: 150px;
  }
  .login,.logo{
    max-width: 400px;
    margin: 20px auto;
  }
</style>
